package com.mtbu.bean;
import java.util.ArrayList;
import java.util.List;

import my.myspring.tool.SpringUtil;

import com.mtbu.bean.base.StepBase;
import com.mtbu.dao.DAOManager;
import com.mtbu.step.StepWorker;
public final class Step extends StepBase {
	
	public Project getProject() throws Exception{
		if (getProjectId() == 0) {
			return null;
		}
		return DAOManager.projectDao.findProject(getProjectId());
	}
	
	public String getDescText() throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("(");
		sb.append(getBeanName() + ":" + getOwnerNames());
		sb.append(")");
		
		return sb.toString();
	}
	
	public String getOwnerNames() throws Exception {
		StringBuffer sb = new StringBuffer();
		
		List<SysUser> listUsers = getOwners();
		for (SysUser usr : listUsers) {
			sb.append(usr.getUserName() + ",");
		}
		try {
			sb.deleteCharAt(sb.length()-1);
		} catch (Exception e) {
			// TODO: handle exception
		}
		

		
		return sb.toString();
	}
	
	public List<SysUser> getOwners() throws Exception {
		List<SysUser> res = new ArrayList<SysUser>();
		List<SysUser> listUsers = DAOManager.sysUserDao.findAll();
		String mark = "," + getId() + ",";
		for (SysUser sysUser : listUsers) {
			String permission = "," + sysUser.getStepPermission() + ",";
			if (permission.indexOf(mark) >= 0) {
				res.add(sysUser);
			}
		}
		
		return res;
	}
	

	public Step getNextStep() throws Exception {
		if (getNextStepId() == 0) {
			return null;
		}
		return DAOManager.stepDao.findStep(getNextStepId());
	}
	
	public Step getPreStep() throws Exception {
		if (getPreStepId() == 0) {
			return null;
		}
		return DAOManager.stepDao.findStep(getPreStepId());
	}
	
	public boolean doWork(){
		StepWorker worker = getStepWorker();
		if (worker == null) {
			return true;
		}
		return worker.doStepWork();
	}
	
	public boolean doRollBack(){
		StepWorker worker = getStepWorker();
		if (worker == null) {
			return true;
		}
		return worker.doStepRollBack();
	}
	
	public StepWorker getStepWorker(){
		StepWorker worker = null;
		try {
			worker = (StepWorker)SpringUtil.getBean(getBeanName().isEmpty() ? 
					"stepWorkerBase" : getBeanName() );
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return worker;
	}
	
	public String toLogString(){
		return "[" 
				+ this.getId() + ","
				+ this.getStatus() + ","
				+ this.getType() + ","
				+ this.getName() + ","
				+ this.getPreStepId() + ","
				+ this.getNextStepId() + "]";
	}
}
